import HeaderNav from "@/components/header-nav"
import styles from "./index.module.less"
import classNames from 'classnames'
import { useEffect, useState, useRef } from "react"
import { Tag, InfiniteScroll, PullToRefresh, DotLoading, Empty } from 'antd-mobile'
import { showErrorToast } from '@/utils/customToast';
const { getDiamondRecords } = $globalServicer('My')
import { useSearchParams } from 'react-router-dom';
const DiamondRecord = () => {
  const PageSize = 10;
  const [page, setPage] = useState(1)
  const [records, setRecords] = useState([])
  const [hasMore, setHasMore] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [loading, setLoading] = useState(false)
  const [noData, setNoData] = useState(false)
  const [isInitialized, setIsInitialized] = useState(false)
  const [activeTab, setActiveTab] = useState('all') // 添加标签页状态
  const [params] = useSearchParams();
  const diamond_balance = params.get('diamond_balance');
  const fetchRecords = async (currentPage = 1) => {
    try {
      const response = await getDiamondRecords({
        page: currentPage,
        size: PageSize,
      })
      
      if (response?.data) {
        return {
          records: response.data,
        }
      }
      return { records: [] }
    } catch (error) {
      showErrorToast("加载失败，请稍后再试")
      return { records: [] }
    }
  }

  const resetStates = () => {
    setPage(1)
    setRecords([])
    setNoData(false)
    setHasMore(true)
    setIsInitialized(false)
  }

  // 初始化数据加载
  useEffect(() => {
    const initializeData = async () => {
      try {
        setLoading(true)
        const { records: newRecords} = await fetchRecords(1)
        
        if (newRecords.length === 0) {
          setNoData(true)
          setHasMore(false)
        } else {
          setRecords(newRecords)
          setHasMore(newRecords.length >= PageSize)
        }
      } catch (error) {
        showErrorToast("加载失败，请稍后再试")
      } finally {
        setLoading(false)
        setIsInitialized(true)
      }
    }

    initializeData()
  }, [])

  // 加载更多数据
  const loadMoreData = async () => {
    // 如果未初始化、没有更多数据、正在加载或刷新，则不加载
    if (!isInitialized || !hasMore || loading || refreshing) return
    
    try {
      setLoading(true)
      const nextPage = page + 1
      const { records: newRecords } = await fetchRecords(nextPage)
      
      if (newRecords.length === 0) {
        setHasMore(false)
        return
      }
      
      setRecords((prevData) => [...prevData, ...newRecords])
      setPage(nextPage)
      setHasMore(newRecords.length >= PageSize)
    } finally {
      setLoading(false)
    }
  }


  // 下拉刷新处理
  const handleRefresh = async () => {
    if (refreshing) return
    
    setRefreshing(true)
    resetStates()
    
    try {
      const { records: newRecords} = await fetchRecords(1)
      if (newRecords.length === 0) {
        setNoData(true)
        setHasMore(false)
      } else {
        setRecords(newRecords)
        setHasMore(newRecords.length >= PageSize)
      }
    } finally {
      setRefreshing(false)
      setIsInitialized(true)
    }
  }

  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>加载中</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 已到达底部 ---</span>
        )}
      </>
    )
  }

  // 过滤记录的函数
  const getFilteredRecords = () => {
    if (activeTab === 'all') {
      return records;
    } else if (activeTab === 'gain') {
      return records.filter(record => Number(record.formatted_amount) > 0);
    } else if (activeTab === 'spend') {
      return records.filter(record => Number(record.formatted_amount) <= 0);
    }
    return records;
  };

  // 格式化时间显示
  const formatTime = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 简化的记录渲染
  const renderRecord = (record) => {
    const amount = Number(record.formatted_amount);
    const isPositive = amount > 0;
    const amountColor = isPositive ? styles.positive : styles.negative;
    
    return (
      <div key={record.id} className={styles.recordItem}>
        <div className={styles.recordInfo}>
          <div className={styles.recordTitle}>{record.type_name || '积分记录'}</div>
          <div className={styles.recordTime}>{formatTime(record.created_at)}</div>
        </div>
        <div className={classNames(styles.recordAmount, amountColor)}>
          {record.symbol}{record.amount}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.page}>
      <HeaderNav title="积分明细" backArrow={true}></HeaderNav>
      
      <div className={styles.mainContent}>
        {/* 标签页导航 */}
        <div className={styles.tabContainer}>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'all' })}
            onClick={() => setActiveTab('all')}
          >
            全部
          </button>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'gain' })}
            onClick={() => setActiveTab('gain')}
          >
            获得
          </button>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'spend' })}
            onClick={() => setActiveTab('spend')}
          >
            消耗
          </button>
        </div>

        {/* 记录列表 */}
        <div className={styles.recordList}>
          <PullToRefresh onRefresh={handleRefresh} refreshing={refreshing}>
            {getFilteredRecords().map(renderRecord)}
            {noData && <Empty description='暂无数据' />}
            
            {/* 无限滚动 */}
            <div style={{ minHeight: '40px' }}>
              {!noData && records.length > 0 && (
                <>
                  {hasMore ? (
                    <InfiniteScroll 
                      loadMore={loadMoreData} 
                      hasMore={hasMore}
                      threshold={250}
                      disabled={loading || refreshing}
                    >
                      <InfiniteScrollContent hasMore={hasMore} />
                    </InfiniteScroll>
                  ) : (
                    <div className={styles.noMoreData}>--- 已到达底部 ---</div>
                  )}
                </>
              )}
            </div>
          </PullToRefresh>
        </div>
      </div>
    </div>
  )
}

export default DiamondRecord